package com.dd.cloud.user.service.chknowl.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dd.cloud.auth.entity.RoleMenu;
import com.dd.cloud.common.constants.ChKnowlConstants;
import com.dd.cloud.user.entity.chknowl.ChknowlBooksCtlg;
import com.dd.cloud.user.entity.chknowl.ChknowlBooksPresent;
import com.dd.cloud.user.mapper.chknowl.ChknowlBooksCtlgMapper;
import com.dd.cloud.user.req.chknowl.ChknowlBooksCtlgReq;
import com.dd.cloud.user.req.chknowl.ChknowlBooksUpdateReq;
import com.dd.cloud.user.res.chknowl.ChknowlBooksChapterRes;
import com.dd.cloud.user.service.chknowl.IChknowlBooksCtlgService;
import com.dd.cloud.user.service.chknowl.IChknowlBooksPresentService;
import com.dd.cloud.common.enums.ZkExceptionEnum;
import com.dd.cloud.common.exception.ZekeException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.ooxml.POIXMLDocument;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;
import java.util.regex.Matcher;
import java.util.stream.Collectors;

/**
 * <p>
 * 古籍目录表 服务实现类
 * </p>
 *
 * @author czg
 * @since 2022-07-04
 */
@Service
@Slf4j
public class ChknowlBooksCtlgServiceImpl extends ServiceImpl<ChknowlBooksCtlgMapper, ChknowlBooksCtlg> implements IChknowlBooksCtlgService {
    @Autowired
    private IChknowlBooksPresentService chknowlBooksPresentService;


    /**
     * 保存word文档里的古籍文章
     *
     * @param files
     */
    @Override
    @Transactional
    public String saveBooksFromWord(MultipartFile[] files, String category) {
//        //返回导入失败的书籍信息, 如果无信息则表示都成功
//        String message = "";
//        for (MultipartFile file :
//                files) {
//            String textFileName = file.getOriginalFilename();
//            Map wordMap = new LinkedHashMap();//创建一个map对象存放word中的内容
//            try {
//                if (textFileName.endsWith(".doc")) { //判断文件格式
//                    InputStream fis = file.getInputStream();
//                    WordExtractor wordExtractor = new WordExtractor(fis);//使用HWPF组件中WordExtractor类从Word文档中提取文本或段落
//                    int i = 1;
//                    for (String words : wordExtractor.getParagraphText()) {//获取段落内容
//                        System.out.println(words);
//                        wordMap.put("DOC文档，第（" + i + "）段内容", words);
//                        i++;
//                    }
//                    fis.close();
//                }
//                if (textFileName.endsWith(".docx")) {
//                    File uFile = new File("tempFile.docx");//创建一个临时文件
//                    if (!uFile.exists()) {
//                        uFile.createNewFile();
//                    }
//                    FileCopyUtils.copy(file.getBytes(), uFile);//复制文件内容
//                    OPCPackage opcPackage = POIXMLDocument.openPackage("tempFile.docx");//包含所有POI OOXML文档类的通用功能，打开一个文件包。
//
//
//                    XWPFDocument document = new XWPFDocument(opcPackage);//使用XWPF组件XWPFDocument类获取文档内容
//                    List<XWPFParagraph> paras = document.getParagraphs();
//                    List<XWPFTable> xwpfTables = document.getTables();
//                    int i = 1;  //行数遍历下标
//                    int k = 0;  //目录是否完结
//                    int j = 1; //目录层级
//                    String first = null;
//                    ChknowlBooksPresent chknowlBooksPresent = new ChknowlBooksPresent();
//                    List<ChknowlBooksCtlg> list = new ArrayList<>();
//                    //书籍名
//                    chknowlBooksPresent.setName(textFileName.replace(".docx", ""));
//                    //书籍大类
////                    chknowlBooksPresent.setCategory(category);
//                    chknowlBooksPresent.setCreateDate(LocalDateTime.now());
//                    chknowlBooksPresent.setStatus(ChKnowlConstants.ContentStatus.NORMAL);
//
//                    StringBuffer sb = new StringBuffer();
//
//                    for (XWPFParagraph paragraph : paras) {
//                        String words = paragraph.getText();
//                        if (words.equals("")) {
//                            continue;
//                        }
//                        if (words.indexOf("/") >= 0) {
//                            words = words.replaceAll("/", Matcher.quoteReplacement("\\"));
//                        }
//                        ChknowlBooksCtlg mechineBooksCatalogue = new ChknowlBooksCtlg();
//                        mechineBooksCatalogue.setStatus(ChKnowlConstants.ContentStatus.NORMAL);
//                        mechineBooksCatalogue.setCreateDate(LocalDateTime.now());
//                        if (!StringUtils.isBlank(words) && words.indexOf("作者：") >= 0 && i < 20) {
//                            chknowlBooksPresent.setAuthor(words.replace("作者：", ""));
//                        }
//                        if (!StringUtils.isBlank(words) && words.indexOf("朝代：") >= 0 && i < 21) {
////                            chknowlBooksPresent.setDynasty(words.replace("朝代：", ""));
//                        }
//                        if (!StringUtils.isBlank(words) && words.indexOf("年份：") >= 0 && i < 22) {
////                            chknowlBooksPresent.setYears(words.replace("年份：", ""));
//                        }
//                        //目录阶段
//                        if (k == 1 && !StringUtils.isBlank(words)) {
//                            if (first == null) {
//                                //第一个目录
//                                if (words.indexOf(" ") >= 0) {
//                                    words = words.replaceAll(" ", "");
//                                }
//                                if (words.indexOf("\t") >= 0) {
//                                    words = words.substring(0, words.indexOf("\t"));
//                                }
//                                if (words.indexOf("-") >= 0) {
//                                    words = words.substring(0, words.indexOf("-"));
//                                }
//                                if (words.indexOf("：") >= 0) {
//                                    words = words.substring(0, words.indexOf("："));
//                                }
//                                mechineBooksCatalogue.setChapterName(words);
//                                mechineBooksCatalogue.setRank(j);
//                                list.add(mechineBooksCatalogue);
//                                first = words;
//                            } else if (first.equals(words)) {
//                                //目录结束, 已经到正文
//                                k = -1;
//                            } else {
//                                j++;
//                                //其他目录
//                                if (words.indexOf(" ") >= 0) {
//                                    words = words.replaceAll(" ", "");
//                                }
//                                if (words.indexOf("\t") >= 0) {
//                                    words = words.substring(0, words.indexOf("\t"));
//                                }
//                                if (words.indexOf("-") >= 0) {
//                                    words = words.substring(0, words.indexOf("-"));
//                                }
//                                if (words.indexOf("：") >= 0) {
//                                    words = words.substring(0, words.indexOf("："));
//                                }
//                                mechineBooksCatalogue.setChapterName(words);
//                                mechineBooksCatalogue.setRank(j);
//                                list.add(mechineBooksCatalogue);
//                            }
//                        }
//                        //目录结束, 正文阶段 收集正文内容到目录表
//                        int n = 0;  //添加的目录下标
//                        if (k == -1) {
//
//                            for (int l = 0; l < list.size(); l++) {
//                                if (words.equals(list.get(l).getChapterName())) {
//                                    if (n != l) {
//                                        n = l;
//                                        list.get(n - 1).setContent(sb.toString());
//                                        sb = new StringBuffer();
//                                    }
//                                    break;
//                                }
//                            }
//                            sb.append(" \\n ");
//                            sb.append("&nbsp;&nbsp;&nbsp;&nbsp;" + words);
//                        }
//
//                        if (!StringUtils.isBlank(words) && (words.trim()).equals("目录") && i < 50 && k != -1) {
//                            k = 1;
//                        }
//
//                        //System.out.println(words);
//                        wordMap.put("第" + i + "行: ", words);
//                        i++;
//                    }
//                    log.info(textFileName + ": 目录" + list.size());
//                    if (list.size() == 0) {
//                        message += textFileName + ",";
//                    } else {
//                        list.get(list.size() - 1).setContent(sb.toString());
//                        chknowlBooksPresentService.save(chknowlBooksPresent);
//                        list.stream().forEach(me -> me.setBookId(chknowlBooksPresent.getId()));
//                        saveBatch(list);
//                    }
//                    uFile.delete();
//                }
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//
//
//            //System.out.println(wordMap);
//        }
//        if (!message.equals("")) {
//            message += "导入失败";
//            System.out.println(message);
//        }
//        return message;
        return "";
    }

    /**
     * 通过bookid查找书籍所有的目录
     *
     * @param bookId
     * @return
     */
    @Override
    public List<ChknowlBooksCtlg> getChknowlBooksCtlgList(Integer bookId) {
        List<ChknowlBooksCtlg> resList = getBaseMapper().getCtlgListByBookId(bookId);
        if(CollectionUtil.isNotEmpty(resList)){
            //递归出书籍目录
            getBookMenuByType(resList);
        }
        return resList;
    }

    @Override
    public ChknowlBooksCtlg getBooksCtlgContent(Integer bookId, Integer rank) {
        return getBaseMapper().getBooksCtlgContent(bookId, rank);
    }

    public List<ChknowlBooksCtlg> getBookMenuByType(List<ChknowlBooksCtlg> list){
        List<ChknowlBooksCtlg> parents = list.stream().filter(item -> item.getPid().equals(0)).collect(Collectors.toList());
        List<ChknowlBooksCtlg> sons = list.stream().filter(item -> !item.getPid().equals(0)).collect(Collectors.toList());
        //集合排序 正序
        parents.sort(Comparator.comparingInt(t -> t.getSort().intValue()));
        if(CollectionUtil.isNotEmpty(sons)){
            parents.forEach(item -> forRoleMenu(item, sons));
        }
        return parents;
   }


    /**
     * 递归下挂小节
     *
     * @param parent
     * @param sons
     */
    public void forRoleMenu(ChknowlBooksCtlg parent, List<ChknowlBooksCtlg> sons) {
        List<ChknowlBooksCtlg> list = sons.stream()
                .filter(item -> item.getPid().equals(parent.getId()))
                .sorted(Comparator.comparingInt(t -> t.getSort().intValue()))
                .collect(Collectors.toList());
        //集合排序 正序
        list.forEach(item -> {
                    if (parent.getSonMenus() == null) {
                        parent.setSonMenus(new ArrayList<>());
                    }
                    parent.getSonMenus().add(item);
                    forRoleMenu(item, sons);
                }
        );
    }


    /**
     * 添加书籍目录
     *
     * @param req
     */
    @Override
    @Transactional
    public void addBooksCtlg(ChknowlBooksCtlgReq req) {
//        Integer rank = getBaseMapper().getCtlyMaxRank(req.getBookId());
//        rank = rank == null ? 1 : rank;
//        QueryWrapper<ChknowlBooksCtlg> qw = new QueryWrapper<>();
//        qw.lambda().eq(ChknowlBooksCtlg::getBookId, req.getBookId())
//                .eq(ChknowlBooksCtlg::getChapterName, req.getChapterName())
//                .ne(ChknowlBooksCtlg::getStatus, ChKnowlConstants.ContentStatus.DELETE);
//        List<ChknowlBooksCtlg> ctlgList = list(qw);
//        if (ctlgList.isEmpty()){
//            rank = ++rank;
//        } else {
//            if (StringUtils.isBlank(req.getSectionName())){
//                throw new ZekeException(400, "目录已存在, 请添加小节");
//            }
//        }
//
//        Integer sectionRank = null;
//        if (!StringUtils.isBlank(req.getSectionName())) {
//            QueryWrapper<ChknowlBooksCtlg> qs = new QueryWrapper<>();
//            qs.lambda().eq(ChknowlBooksCtlg::getBookId, req.getBookId())
//                    .eq(ChknowlBooksCtlg::getChapterName, req.getChapterName())
//                    .eq(ChknowlBooksCtlg::getSectionName, req.getSectionName())
//                    .ne(ChknowlBooksCtlg::getStatus, ChKnowlConstants.ContentStatus.DELETE);
//            List<ChknowlBooksCtlg> ctlgStr = list(qs);
//            if (!ctlgStr.isEmpty()){
//                throw new ZekeException(400, "该小节已存在");
//            }
//            sectionRank = getBaseMapper().getCtlySectionMaxRank(req.getChapterName());
//            sectionRank = sectionRank == null ? 1 : ++sectionRank;
//        }
//        ChknowlBooksCtlg ctlg = new ChknowlBooksCtlg();
//        BeanUtils.copyProperties(req, ctlg);
//        ctlg.setRank(rank);
//        ctlg.setSectionRank(sectionRank);
//        ctlg.setCreateDate(LocalDateTime.now());
//        ctlg.setStatus(ChKnowlConstants.ContentStatus.NORMAL);
//        boolean flag = save(ctlg);
//        if (!flag) {
//            throw new ZekeException(ZkExceptionEnum.ADD_ERROR);
//        }
    }

    /**
     * 修改书籍内容
     * @param req
     */
    @Override
    @Transactional
    public void updateBooksCtlg(ChknowlBooksUpdateReq req) {
//        ChknowlBooksCtlg ctlg = getById(req.getCtlgId());
//        if (ctlg == null){
//            throw new ZekeException(400, "书籍内容不存在");
//        }
//        if (!ctlg.getChapterName().equals(req.getChapterName())){
//            //修改了目录名
//            QueryWrapper<ChknowlBooksCtlg> qw = new QueryWrapper<>();
//            qw.lambda().eq(ChknowlBooksCtlg::getBookId, req.getBookId())
//                    .eq(ChknowlBooksCtlg::getChapterName, req.getChapterName())
//                    .ne(ChknowlBooksCtlg::getStatus, ChKnowlConstants.ContentStatus.DELETE);
//            List<ChknowlBooksCtlg> ctlgList = list(qw);
//            if (!ctlgList.isEmpty()){
//                throw new ZekeException(400,"目录名已存在");
//            }
//        }
//        if (!StringUtils.isBlank(req.getSectionName())
//                && !req.getSectionName().equals(ctlg.getSectionName())){
//            //修改了小节名
//            QueryWrapper<ChknowlBooksCtlg> qs = new QueryWrapper<>();
//            qs.lambda().eq(ChknowlBooksCtlg::getBookId, req.getBookId())
//                    .eq(ChknowlBooksCtlg::getChapterName, req.getChapterName())
//                    .eq(ChknowlBooksCtlg::getSectionName, req.getSectionName())
//                    .ne(ChknowlBooksCtlg::getStatus, ChKnowlConstants.ContentStatus.DELETE);
//            List<ChknowlBooksCtlg> ctlgStr = list(qs);
//            if (!ctlgStr.isEmpty()){
//                throw new ZekeException(400, "该小节已存在");
//            }
//        }
//        BeanUtils.copyProperties(req, ctlg);
//        boolean flag = updateById(ctlg);
//        if (!flag) {
//            throw new ZekeException(ZkExceptionEnum.ADD_ERROR);
//        }
    }
}
